package com.tyk.bookstore.back.auth.util;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
public class RedisUtil {

	public static StringRedisTemplate stringRedisTemplate;

	public static final String LOGIN_CAPTCHA_KEY_PREFIX = "login:captcha:";

	public static final Duration LOGIN_CAPTCHA_TIMEOUT = Duration.ofMinutes(5);

	public RedisUtil(StringRedisTemplate stringRedisTemplate) {
		RedisUtil.stringRedisTemplate = stringRedisTemplate;
	}

	/**
	 * 设置登录验证码
	 * @param principal 认证主体（邮箱或手机号）
	 * @param captcha 六位数字验证码
	 */
	public static void setLoginCaptcha(String principal, String captcha) {
		stringRedisTemplate.opsForValue().set(LOGIN_CAPTCHA_KEY_PREFIX + principal, captcha, LOGIN_CAPTCHA_TIMEOUT);
	}

	/**
	 * 校验登录验证码
	 * @param principal 认证主体（邮箱或手机号）
	 * @param captcha 六位数字验证码
	 * @return 校验成功返回true, 否则返回false
	 */
	public static boolean equalsLoginCaptcha(String principal, String captcha) {
		return captcha.equals(stringRedisTemplate.opsForValue().get(LOGIN_CAPTCHA_KEY_PREFIX + principal));
	}

	public static void removeLoginCaptcha(String principal) {
		stringRedisTemplate.delete(LOGIN_CAPTCHA_KEY_PREFIX + principal);
	}

}
